package com.justgame.project.service.system.service.impl;

import com.justgame.project.base.servcice.BasicServiceImpl;
import com.justgame.project.cloud.base.entity.CurrentUser;
import com.justgame.project.service.system.entity.SysUserInfo;
import com.justgame.project.service.system.entity.SysUserOperationLog;
import com.justgame.project.service.system.mapper.SysUserOperationLogMapper;
import com.justgame.project.service.system.service.ISysUserOperationLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 *
 * 用户功能操作间隔限制表服务实现类
 *
 * @@tableName sys_user_operation_log
 * @author Zwb
 */
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class SysUserOperationLogServiceImpl extends BasicServiceImpl<SysUserOperationLogMapper, SysUserOperationLog> implements ISysUserOperationLogService {
    @Override
    public void doOperation(CurrentUser currentUser, SysUserOperationLog.Operation operation, Duration duration) {
        findByUserInfoIdIsAndOperationIs(currentUser.getId(),operation).ifPresentOrElse(
                log -> {
                    Assert.isTrue(log.getEndDate().isBefore(LocalDateTime.now()),"您最近已经次操作过了哦");
                    updateByStartDateAndEndDate(log,LocalDateTime.now(),LocalDateTime.now().plus(duration));
                },
                () -> saveOperationLog(currentUser.getId(),operation,LocalDateTime.now().plus(duration))
        );
    }
}
